using System;
using System.Collections;
using System.Web;
using System.Web.Mvc;

namespace Pronghorn.Core
{
	public class ProngHornControllerFactory : DefaultControllerFactory
	{
		public ProngHornControllerFactory(IIocContainer container)
		{
			Container = container;
		}

		public IIocContainer Container
		{
			get; set;
		}

		protected override IController GetControllerInstance(Type controllerType)
		{
			if (controllerType == null)
			{
			    throw new HttpException(0x194, string.Format("The controller for path '{0}' could not be found or it does not implement IController.", RequestContext.HttpContext.Request.Path));
			}
			var url = RequestContext.HttpContext.Request.RawUrl;
			var requestParameters = RequestContext.HttpContext.Request.Params;
			var controller = Container.Resolve<ProngHornControllerBase>(controllerType.FullName,
				new Hashtable
					{
						{"viewDataDictionary", new ViewDataDictionary<IProngHornSkinContext>(Container.Resolve<IProngHornSkinContext>())},
						{"siteContext",Container.Resolve<ISiteService>().GetSiteContext(url, requestParameters)},
						{"container", Container}
					});
			return controller;
		}

		public override void ReleaseController(IController controller)
		{
			var disposable = controller as IDisposable;
			if (disposable != null)
			{
			    disposable.Dispose();
			}
			Container.Release(controller);
		}
	}
}